package com.caowei.weicimpress.weicimpress;

import android.content.Context;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.caowei.weicimpress.weicimpress.widget.DropdownListWidget;
import com.caowei.weicimpress.weicimpress.widget.LeftActionbarDropdownListWidget;
import com.caowei.weicimpress.weicimpress.widget.Toast;

import java.io.File;
import java.util.ArrayList;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class MainActivity extends BaseActivity implements View.OnClickListener,
        ActionBarBaseFragment.GainActionbarLayout,
        ActionBarBaseFragment.OnRefreshFragment ,
        BaseFragment.GetFragment,BaseFragment.OnSwitchFragment {
    private final static String TAG=MainActivity.class.getSimpleName();
    private final static int DEFAULT_OFFSCREEN_PAGES=4;
    //保存状态使用
    private static final String INSTANCESTATE_TAB ="INSTANCESTATE_TAB";
    @InjectView(R.id.pager)
    ViewPager mViewPager;
    private TabsAdapter mTabsAdapter;
    @InjectView(R.id.actionbarLayout)
    RelativeLayout actionbarLayout;
    @InjectView(R.id.pathlayout1)
    LinearLayout pathlayout1;
    @InjectView(R.id.pathlayout2)
    LinearLayout pathlayout2;
    private LeftActionbarDropdownListWidget listWidget1;
    private DropdownListWidget listWidget2;
    private DropdownListWidget menuListWidget;

    private long lastBackTime=0;
    private Menu mMenu;
    private NotifyChangeBroadcastReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);

        init();

        mViewPager.setOffscreenPageLimit(DEFAULT_OFFSCREEN_PAGES);

        Bundle bundle=new Bundle();
      //  bundle.putSerializable("pathlayout",pathlayout1);
        mTabsAdapter = new TabsAdapter(this, mViewPager);
        ActionBar.Tab tab= bar.newTab();
        mTabsAdapter.addTab(tab.setText(R.string.sysfile),
                SysFileFragment.class, bundle,pathlayout1);
        bundle=new Bundle();
      //  bundle.putSerializable("pathlayout",pathlayout2);
        tab= bar.newTab();
        mTabsAdapter.addTab(tab.setText(R.string.compressfile),
                CompressFileFragment.class, bundle,pathlayout2);
        bundle=new Bundle();
        mTabsAdapter.addTab(bar.newTab().setText(R.string.searchfiletab),
                SearchFragment.class, bundle,null);

        bundle=new Bundle();
        mTabsAdapter.addTab(bar.newTab().setText(R.string.task),
                TaskFragment.class, bundle,null);

        int tabIndex=(savedInstanceState==null)?Utils.SYSFRAG_TAB_INDEX:
                savedInstanceState.getInt(INSTANCESTATE_TAB,Utils.SYSFRAG_TAB_INDEX);

        /*int tabIndex=PreferenceManager.getDefaultSharedPreferences(this).getInt(INSTANCESTATE_TAB,
                Utils.SYSFRAG_TAB_INDEX);*/
        bar.setSelectedNavigationItem(tabIndex);

        //todo 测试压缩 frag  以后删除
//        bar.setSelectedNavigationItem(0);

        receiver=new NotifyChangeBroadcastReceiver ();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Utils.NOTIFYTASKCHANGE_ACTION);
        intentFilter.addAction(Utils.NOTIFYFILESYSTEMCHANGEINCURRENTDIR_ACTION);
        intentFilter.addAction(Utils.NOTIFYCOMPRESSSYSTEMCHANGE_ACTION);
        receiver.setTaskFragment((TaskFragment) mTabsAdapter.getItem(Utils.TASKFRAG_TAB_INDEX));
        receiver.setSysFileFragment((SysFileFragment) mTabsAdapter.getItem(Utils.SYSFRAG_TAB_INDEX));
        receiver.setCompressFileFragment((CompressFileFragment) mTabsAdapter.getItem(Utils.COMPRESSFRAG_TAB_INDEX));
        registerReceiver(receiver, intentFilter);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        int selectTabIndex= bar.getSelectedNavigationIndex();
        outState.putInt(INSTANCESTATE_TAB,selectTabIndex);
       /* SharedPreferences.Editor editor= PreferenceManager.getDefaultSharedPreferences(this).edit();
        editor.putInt(INSTANCESTATE_TAB,selectTabIndex);
        editor.commit();*/
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    @Override
    protected void initactioBar() {
        ActionBar actionBar=getSupportActionBar();
        bar=actionBar;
        actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE|ActionBar.DISPLAY_USE_LOGO);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        View v= LayoutInflater.from(this).inflate(R.layout.actionbar_custom,null,false);
        actionBar.setCustomView(v);
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME|
                ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setHomeAsUpIndicator(R.drawable.up);
    }

    private void init() {
        listWidget1=new LeftActionbarDropdownListWidget(this,new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG,"onItemClick");

            }
        });
        listWidget1.setWidth(280);

        pathlayout1.setTag(listWidget1);
        listWidget2=new LeftActionbarDropdownListWidget(this,new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG,"onItemClick");

            }
        });
        listWidget2.setWidth(280);
        pathlayout2.setTag(listWidget2);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        mMenu=menu;
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        mMenu=menu;
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Log.d(TAG, "actionBar.getHeight()=" + getSupportActionBar().getHeight());
        switch (item.getItemId()) {
            case android.R.id.home:
                if(mMenu!=null){
                    View searchView= MenuItemCompat.getActionView(mMenu.findItem(R.id.search));
                    if(searchView instanceof OnIndicatorOrQueryClick){
                        ((OnIndicatorOrQueryClick)searchView).onIndicatorClick();
                    }
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        int action=event.getAction();
        if((KeyEvent.ACTION_DOWN==action)&&(keyCode==KeyEvent.KEYCODE_BACK)){
            int selectIndex= bar.getSelectedNavigationIndex();
            TabsAdapter adapter = (TabsAdapter) mViewPager.getAdapter();
            BaseFragment fr= (BaseFragment) adapter.getItem(selectIndex);
            if(mMenu!=null){
                MenuItem search=mMenu.findItem(R.id.search);
                MySearchView v= (MySearchView) MenuItemCompat.getActionView(search);
                if(v!=null&&!v.isIconified()){
                    OnIndicatorOrQueryClick onIndicatorOrQueryClick= (OnIndicatorOrQueryClick) v;
                    onIndicatorOrQueryClick.onIndicatorClick();
                    return true;
                }
            }
            if(ActionBarBaseFragment.class.isAssignableFrom(((Object) fr).getClass())){
                ActionBarBaseFragment barBaseFragment= (ActionBarBaseFragment) fr;
                if(barBaseFragment.performBack()==-1){
                    repeatPressMenuExit();
                }
            }
/*
            if(ActionBarBaseFragment.class.isAssignableFrom(((Object) fr).getClass())){
                ActionBarBaseFragment barBaseFragment= (ActionBarBaseFragment) fr;
                if(barBaseFragment.performBack()==-1){
                    repeatPressMenuExit();
                }
            }else if(fr instanceof SearchFragment){
                if(mMenu!=null){
                    MenuItem search=mMenu.findItem(R.id.search);
                    View v= MenuItemCompat.getActionView(search);
                    if(v instanceof OnIndicatorOrQueryClick){
                        OnIndicatorOrQueryClick onIndicatorOrQueryClick= (OnIndicatorOrQueryClick) v;
                        onIndicatorOrQueryClick.onIndicatorClick();
                    }
                }
            }else {
                repeatPressMenuExit();
            }*/
        }
        return true;
    }


    private void repeatPressMenuExit(){
        if(System.currentTimeMillis()-lastBackTime>Utils.EXITINTERVAL){
            Toast.makeText(this,getResources().getString(R.string.repeatpressexit),
                    Toast.LENGTH_SHORT).show();
            lastBackTime=System.currentTimeMillis();
        }else{
            Utils.exit();
        }
    }

    @OnClick({R.id.pathlayout1,R.id.pathlayout2})
    @Override
    public void onClick(View v) {
        int id=v.getId();
        switch (id){
            case R.id.pathlayout1:
                if(!listWidget1.isShowing()){
                    listWidget1.show(v);
                }else{
                    listWidget1.dismiss();
                }
                break;
            case R.id.pathlayout2:
                if(!listWidget2.isShowing()){
                    listWidget2.show(v);
                }else{
                    listWidget2.dismiss();
                }
                break;
        }
    }

    @Override
    public RelativeLayout gainActionbarLayout() {
        return actionbarLayout;
    }

    @Override
    public void switchFragment(final Class<? extends BaseFragment> fragmentCls,BaseFragment.Callback callback) {
        final TabsAdapter adapter= (TabsAdapter) mViewPager.getAdapter();
        if(fragmentCls.equals(SysFileFragment.class)){
            bar.setSelectedNavigationItem(Utils.SYSFRAG_TAB_INDEX);

            callback.onCallback(new BaseFragment.Callback1() {
                @Override
                public void onCallback(Object... objects) {
                    Class<? extends BaseFragment> cl= (Class<? extends BaseFragment>) objects[0];
                    SysFileFragment frgament= (SysFileFragment) adapter.getItem(
                            Utils.SYSFRAG_TAB_INDEX);
                    if(cl.equals(SearchFragment.class)){

                    }else if(cl.equals(CompressFileFragment.class)){
                        frgament.selectDir();
                    }
                }
            });
            //todo
        }else if(fragmentCls.equals(CompressFileFragment.class)){
            bar.setSelectedNavigationItem(Utils.COMPRESSFRAG_TAB_INDEX);
            if(callback!=null){
                callback.onCallback(new BaseFragment.Callback1() {
                    @Override
                    public void onCallback(Object... objects) {
                        Class<? extends BaseFragment> cl= (Class<? extends BaseFragment>) objects[0];
                        CompressFileFragment frgament= (CompressFileFragment) adapter.getItem(
                                Utils.COMPRESSFRAG_TAB_INDEX);
                        if(cl.equals(SysFileFragment.class)){
                            File compressRootFile=new File((String) objects[1]);
                            if(!compressRootFile.equals(frgament.getRootFile())){
                                frgament.setRootFile(compressRootFile);
                                frgament.refreshFromRootFile();
                            }
                        }else if(cl.equals(SearchFragment.class)){
                            File compressRootFile= (File) objects[1];
                            if(!compressRootFile.equals(frgament.getRootFile())){
                                frgament.setRootFile(compressRootFile);
                                frgament.refreshFromRootFile();
                            }
                        }
                    }
                });
            }

        }else if(fragmentCls.equals(SearchFragment.class)){
            bar.setSelectedNavigationItem(Utils.SEARCH_TAB_INDEX);
            if(callback!=null){
                callback.onCallback(new BaseFragment.Callback1() {
                    @Override
                    public void onCallback(Object... objects) {
                        SearchFragment frgament= (SearchFragment) adapter.getItem(
                                Utils.SEARCH_TAB_INDEX);
                        frgament.setRootFile((File) objects[3]);
                        frgament.setCurrentPath((String) objects[4]);
                        frgament.setSearchStr((String) objects[1]);
                        frgament.setmData((java.util.List<FileInfoBean>) objects[2]);
                        frgament.setSelectedFrgament((ActionBarBaseFragment) objects[5]);
                        frgament.refresh();
                    }
                });
            }
        }

    }

    @Override
    public void onRefresh(int fragmentIndex) {
        TabsAdapter adapter= (TabsAdapter) mViewPager.getAdapter();
        ActionBarBaseFragment frgament= (ActionBarBaseFragment) adapter.getItem(
                fragmentIndex);
        frgament.refresh();
    }


    @Override
    public BaseFragment get(int index) {
        TabsAdapter adapter= (TabsAdapter) mViewPager.getAdapter();
        Fragment frgament=  adapter.getItem(index);
        return (BaseFragment) frgament;
    }


    public static class TabsAdapter extends FragmentPagerAdapter
            implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
        private final Context mContext;
        private final ActionBar mActionBar;
        private final ViewPager mViewPager;
        private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

        static final class TabInfo {
            private final Class<?> clss;
            private final Bundle args;
            private Fragment fragment;
            private LinearLayout actionbarpathlayout;
            TabInfo(Class<?> _class, Bundle _args,LinearLayout actiobarLinearLayout) {
                clss = _class;
                args = _args;
                this.actionbarpathlayout=actiobarLinearLayout;
            }
        }

        public TabsAdapter(ActionBarActivity activity, ViewPager pager) {
            super(activity.getSupportFragmentManager());
            mContext = activity;
            mActionBar = activity.getSupportActionBar();
            mViewPager = pager;
            mViewPager.setAdapter(this);
            mViewPager.setOnPageChangeListener(this);
        }

        public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args,LinearLayout actiobarLinearLayout) {
            TabInfo info = new TabInfo(clss, args,actiobarLinearLayout);
            tab.setTag(info);
            tab.setTabListener(this);
            mTabs.add(info);
            mActionBar.addTab(tab);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mTabs.size();
        }

        @Override
        public Fragment getItem(int position) {
            TabInfo info = mTabs.get(position);
            if (info.fragment == null) {
                info.fragment = Fragment.instantiate(mContext, info.clss.getName(), info.args);
            }
            return info.fragment;
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            mActionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }

        @Override
        public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
            TabInfo info = (TabInfo) tab.getTag();
            for (int i=0; i<mTabs.size(); i++) {
                if (mTabs.get(i).equals(info)) {
                    mViewPager.setCurrentItem(i);
                }
            }
            LinearLayout layout=info.actionbarpathlayout;
            if(layout!=null&&layout.getVisibility()!=View.VISIBLE){
                layout.setVisibility(View.VISIBLE);
            }
            final TabsAdapter adapter= (TabsAdapter) mViewPager.getAdapter();

            if(mContext instanceof MainActivity){
                MainActivity mainActivity= (MainActivity) mContext;
                if(mainActivity.mMenu!=null){
                    Class cl= ((Object)adapter.getItem(mViewPager.getCurrentItem())).getClass();
                    View searchView= MenuItemCompat.getActionView(mainActivity.mMenu.findItem(R.id.search));
                    if(cl.equals(SearchFragment.class)){
                        if(searchView instanceof OnIndicatorOrQueryClick){
                            ((OnIndicatorOrQueryClick)searchView).onSearchBtnClick();
                            ((OnIndicatorOrQueryClick)searchView).onHideSearchBtn(false);
                        }
                    }else if(ActionBarBaseFragment.class.isAssignableFrom(cl)){
                        if(searchView instanceof OnIndicatorOrQueryClick){
                            ((OnIndicatorOrQueryClick)searchView).onRebackActionbar();
                            ((OnIndicatorOrQueryClick)searchView).onHideSearchBtn(false);
                        }
                    }else if(TaskFragment.class.isAssignableFrom(cl)){
                        if(searchView instanceof OnIndicatorOrQueryClick){
                            ((OnIndicatorOrQueryClick)searchView).onRebackActionbar();
                            ((OnIndicatorOrQueryClick)searchView).onHideSearchBtn(true);
                        }
                    }
                }
            }


           /* if(!tab.getText().equals(mContext.getString(R.string.tab_sd))) {
                ActionMode actionMode = ((MainActivity) mContext).getActionMode();
                if (actionMode != null) {
                    actionMode.finish();
                }
            }*/
        }

        @Override
        public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
            TabInfo info = (TabInfo) tab.getTag();
            LinearLayout layout=info.actionbarpathlayout;
            if(layout!=null&&layout.getVisibility()==View.VISIBLE){
                layout.setVisibility(View.GONE);
            }
        }

        @Override
        public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {

        }
    }

    public static interface OnIndicatorOrQueryClick{
        public void onIndicatorClick();
        public void onSearchBtnClick();
        public void onRebackActionbar();
        public void onHideSearchBtn(boolean hide);
    }



}
